package devbureau.fstore.common.load.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import devbureau.fstore.common.Item;
import devbureau.fstore.common.load.FileParser;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

public class CSVFileParser implements FileParser {
	
	static Logger logger = Logger.getLogger(CSVFileParser.class);

	private List<Item> items = null;
	// TODO: Make more complex expression
	private static final String MATCH_REGEXP = "^.*;.*;.*;.*;.*;.*$";
	private static final String SPLIT_REGEXP = ";";

	@Override
	public List<Item> parse(byte[] fileData) throws Exception {
		logger.debug("#parse enter");
		init();
		StringBuffer errors = new StringBuffer();
		try{
            ByteArrayInputStream bais = new ByteArrayInputStream(fileData);
			BufferedReader br = new BufferedReader(new InputStreamReader(bais));
			String line = null;
			int number = 0;
			while((line = br.readLine()) != null){
				if(number != 0 ) {
					try{
						items.add(parseLine(line));
					}catch(Exception ex){
						errors.append("\nВ строке " + number + " ошибка : " + ex.getMessage() );	
					}
				}
				number++;
			}
		}catch(IOException ex){
			logger.error(ex,ex);
			throw new Exception("\nОшибка чтения данных.\n Ошибка : '"+ex.getMessage()+"'.");
		}
		
		if(errors.length()>0) {
			throw new Exception("\nОшибка разбора данных.\n Ошибки : " + errors.toString());
		}
		logger.debug("#parse exit");
		return items;
	}

	private void init() {
		items = new ArrayList<Item>();
	}

	Item parseLine(String line) throws Exception {
		logger.trace("#parseLine enter");
		
		Item item = null;
		
		if(line.matches(MATCH_REGEXP)) {
			String[] data = line.split(SPLIT_REGEXP);
            item =HelperFileParser.parseData(data);

		}else{
			throw new Exception("Строка '" + line + "' не соответствует формату '"+MATCH_REGEXP+"'.");
		}
		
		logger.trace("#parseLine exit");
		return item;
	}
}
